<template>
    <el-drawer v-model="showDrawer"
               :title="title"
               :size="dynamicSize"
               :close-on-click-modal="false"
               :destroy-on-close="destroyOnClose">
        <div class="formDrawer">
            <div class="body">
                <slot></slot>
            </div>
            <div class="actions">
                <el-button type="primary" @click="submit" :loading="loading">{{ confirmText }}</el-button>
                <el-button type="default" @click="close">取消</el-button>
            </div>
        </div>
    </el-drawer>
</template>

<script setup>
    import { ref, computed, onMounted, onUnmounted } from "vue"

    const showDrawer = ref(false)

    const props = defineProps({
        title: String,
        size: {
            type: String,
            default: "45%"
        },
        mobileSize: {
            type: String,
            default: "100%"
        },
        mobileBreakpoint: {
            type: Number,
            default: 768
        },
        destroyOnClose: {
            type: Boolean,
            default: false
        },
        confirmText: {
            type: String,
            default: "提交"
        }
    })

    // 响应式窗口宽度检测
    const windowWidth = ref(window.innerWidth)

    const updateWindowWidth = () => {
        windowWidth.value = window.innerWidth
    }

    onMounted(() => {
        window.addEventListener('resize', updateWindowWidth)
    })

    onUnmounted(() => {
        window.removeEventListener('resize', updateWindowWidth)
    })

    // 动态计算尺寸
    const dynamicSize = computed(() => {
        return windowWidth.value <= props.mobileBreakpoint ? props.mobileSize : props.size
    })

    const loading = ref(false)
    const showLoading = () => loading.value = true
    const hideLoading = () => loading.value = false

    // 打开
    const open = () => showDrawer.value = true

    // 关闭
    const close = () => showDrawer.value = false

    // 提交
    const emit = defineEmits(["submit"])
    const submit = () => emit("submit")

    // 向父组件暴露以下方法
    defineExpose({
        open,
        close,
        showLoading,
        hideLoading
    })
</script>

<style>
    .formDrawer{
        width: 100%;
        height: 100%;
        position: relative;
        @apply flex flex-col;
    }

    .formDrawer .body{
        flex: 1;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 50px;
        overflow-y: auto;
    }

    .formDrawer .actions{
        height: 50px;
        @apply mt-auto flex items-center;
    }

    /* 移动端适配 */
    @media (max-width: 768px) {
        .formDrawer .actions {
            padding: 0 16px;
        }

        .formDrawer .body {
            padding: 0 16px;
        }
    }
</style>
